package com.project.springboot.config;

import com.project.springboot.enumparam.IdCodeToEnumConverterFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

/**
 * description: web配置类
 * @author 朱正磊
 * @date 2024-01-18 14:58:44
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    /**
     * description: 注册类型转换器工厂
     * @author 朱正磊
     * @date 2024-01-18 15:02:18
     * @param registry 注册器
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverterFactory(new IdCodeToEnumConverterFactory());
    }

    /**
     * description: 注册语言环境拦截器，对所有的请求都适用
     * @author 朱正磊
     * @date 2025-06-13 14:50:27
     * @param registry 拦截器注册器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(this.localeChangeInterceptor()).addPathPatterns("/**");
    }

    /**
     * description: 拦截器，用于拦截用户的请求，根据用户请求参数来设置语言环境
     * @author 朱正磊
     * @date 2025-06-13 14:50:19
     * @return 返回拦截器
     */
    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
        // 受 GET 请求
        interceptor.setHttpMethods(HttpMethod.GET.name());
        // 传递客户端语言的查询参数
        interceptor.setParamName("_lang");
        // 忽略客户端非法的参数
        interceptor.setIgnoreInvalidLocale(true);
        return interceptor;
    }

}
